//
//  FileContentViewController.swift
//  GiteeClient
//
//  Created by 王志标 on 2020/10/23.
//

import UIKit
import PKHUD
import WebKit

/// 文件查看控制器
class FileContentViewController: BaseViewController {

    var projectModel:ProjectMdoel!
    var currentPath:String = ""
    var projectName:String = ""
    
    var contentWebView:WKWebView!
    
    var model:BolbModel?{
        didSet{
            guard let html = model?.content else {
                return
            }
            self.render(html: html)
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        loadData()
    }
    
    init(pid: ProjectMdoel,path:String,name:String) {
        super.init(nibName: nil, bundle: nil)
        self.projectModel = pid
        self.currentPath = path
        self.projectName = name
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI(){
        self.title = self.projectName
        
        let config = WKWebViewConfiguration()
        let script = "var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta); "
        
        let userScript = WKUserScript(source: script, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
        let wkuserConter = WKUserContentController()
        wkuserConter.addUserScript(userScript)
        config.userContentController = wkuserConter
        config.dataDetectorTypes = .all
        var frame = view.bounds
        frame.size.height -= Common.topHeight
        contentWebView = WKWebView(frame: frame, configuration: config)
        view.addSubview(contentWebView)
    }
    
    
    func render(html: String){
        
        let lang = projectName.split(separator: ".").last!.description
        let theme = "github"
        let formatPath = Bundle.main.path(forResource: "code", ofType: "html")
        let highlightJsPath = Bundle.main.path(forResource: "highlight.pack", ofType: "js")
        let themeCssPath = Bundle.main.path(forResource: theme, ofType: "css")
        let codeCssPath = Bundle.main.path(forResource: "code", ofType: "css")
        
        let lineNums = "true"
        let format = try! String.init(contentsOfFile: formatPath!, encoding: String.Encoding.utf8)
        let escapedCode = File.escapeHTML(html: html)
        let contentHtml = NSString.init(format: format as NSString, themeCssPath!,codeCssPath!,highlightJsPath!,lineNums,lang,escapedCode).description
      
        contentWebView.loadHTMLString(contentHtml , baseURL: Bundle.main.bundleURL)
    }
    
    func loadData() {
        
        if projectModel == nil {
            HUD.flash(.label("项目为空"))
            return
        }
        
        HUD.show(.progress)
        DispatchQueue.global().async {
            var url = URLs.DETIAL_URL + self.projectModel.id.description + "/repository/files"
            url += "?file_path=\(self.currentPath)\(self.projectName)&ref=master"
            
            let content_url = url.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!
            
            let result:Result<BolbModel> = NetWorkTool.shared.getRequest(url: content_url, parameters:nil)
                
            DispatchQueue.main.async {
                HUD.hide()
                if result.code == 0 {
                    self.model = result.data
                }else {
                    HUD.flash(.label(result.message), delay: 2.0)
                }
            }
        }
    }
    
}
